const DataLoader = require('dataloader')
import { Comment } from '../../models'
import { groupData, placeData } from '../../lib/graphql'

export const commentLoader = () =>
  new DataLoader(
    async keys => {
      let data = await Comment.findAll({ where: { id: { $in: keys } } })
      return placeData(keys, data, 'id')
    },
    { cacheKeyFn: key => key.toString() }
  )

export const commentLoaderByAnswer = () =>
  new DataLoader(
    async keys => {
      const data = await Comment.findAll({
        where: { targetId: { $in: keys }, scope: 'answer', hasData: true },
        order: [['createdAt', 'ASC']]
      })
      return groupData(keys, data, 'targetId')
    },
    { cacheKeyFn: key => 'answer' + key.toString() }
  )

export const likedLoaderByProgress = context =>
  new DataLoader(
    async keys => {
      const { user } = context
      const data = await Comment.findAll({
        where: {
          targetId: { $in: keys },
          scope: 'progress',
          hasData: false,
          userId: user.id
        }
      })
      let result = groupData(keys, data, 'targetId', false)
      return result
    },
    { cacheKeyFn: key => 'progresslike' + key.toString() }
  )

export const likedLoaderByAnswer = context =>
  new DataLoader(
    async keys => {
      const { user } = context
      const data = await Comment.findAll({
        where: {
          targetId: { $in: keys },
          scope: 'answer',
          hasData: false,
          userId: user.id
        }
      })
      let result = groupData(keys, data, 'targetId', false)
      return result
    },
    { cacheKeyFn: key => 'answerlike' + key.toString() }
  )
